import { mapGetters } from 'vuex'
import { upsert, detail, IUpsertParams, IDetailParams, pageList } from '@/api/commonInstance'
import { DBNames } from '@/enum/dbName'

interface ISelectKey {
  key: string
  options: string
}

interface IOptions {
  label: string
  value: string
}

interface ITreeKey {
  key: string
  refName: string
}

interface IAddEditMixinParams {
  treeKey?: ITreeKey[]
  selectKey?: ISelectKey[]
  templateName: string
  enterpriseTemplateName: string // 企业名称数据来源表名
}

export default (params: IAddEditMixinParams) => {
  const {
    selectKey,
    treeKey,
    templateName,
    enterpriseTemplateName = 'B_CONSOLE_LAND', // 临时测试时候土地表名，需要换成企业表名
  } = params

  const mixin = {
    data() {
      return {
        templateName: DBNames[templateName],
        type: 1, // 1: 新增 2: 编辑
        id: null, // 当前id
        loading: false, // 加载状态
        isShowDialog: false, // 弹框状态
        isShowMap: false, // 地图选点组件状态
        interpriseNameOptions: [], // 企业名称选项
        nameLoading: false, // 搜索企业时的状态
      }
    },
    methods: {
      open(type: number = 1, id?: string) {
        // @ts-ignore
        this.type = type
        // @ts-ignore
        this.isShowDialog = true

        if (type === 2 && id) {
          // @ts-ignore
          const { templateName } = this
          this.getDetail({ id, templateName })
        }
      },

      async getDetail(params: IDetailParams) {
        // @ts-ignore
        this.loading = true
        const result = await detail(params)
        // @ts-ignore
        this.id = params.id
        this.initForm(result.data)
        // @ts-ignore
        if (result.data.belongEnterpriseLabel) {
          // @ts-ignore
          this.remoteMethod(result.data.belongEnterpriseLabel)
        }
        // @ts-ignore
        this.loading = false
      },

      initForm(data: any) {
        const { form } = this as any
        Object.keys(form).forEach((key) => {
          const value = data[key]
          if (value) {
            form[key] = value
          }
        })
      },

      handleOk() {
        const { type, form, id, templateName } = this as any
        // @ts-ignore
        this.$refs.ruleForm.validate(async (valid: boolean) => {
          if (valid) {
            // @ts-ignore
            this.loading = true
            const params: IUpsertParams = {
              data: form,
              templateName,
            }
            if (type === 2) {
              params.id = id
            }
            await upsert(params)
            // @ts-ignore
            this.loading = false
            // @ts-ignore
            this.isShowDialog = false
            // @ts-ignore
            this.$emit('onRefresh')
          }
        })
      },

      handleCloseDialog() {
        // @ts-ignore
        this.$refs.ruleForm?.resetFields()
      },

      handleAddContacts() {
        // @ts-ignore
        this.form.contacts.push({
          name: '',
          phone: '',
        })
      },

      handleDelContacts(index: number) {
        // @ts-ignore
        this.form.contacts.splice(index + 1, 1)
      },

      handleIndustryChange() {},

      async remoteMethod(query: string) {
        if (query.trim() !== '') {
          // @ts-ignore
          this.nameLoading = true
          const params = {
            conditions: { 'data.name': { $regex: query } },
            pageInfo: {
              pageNum: 1,
              pageSize: 10,
            },
            templateName: DBNames[enterpriseTemplateName], // 后期需要换成企业库表名
          }
          // @ts-ignore
          const { list } = await pageList(params)
          // @ts-ignore
          this.interpriseNameOptions = list.map((d) => ({
            label: d.data.name,
            value: d.id,
            detail: d.data,
          }))
          // @ts-ignore
          this.nameLoading = false
        } else {
          // @ts-ignore
          this.interpriseNameOptions = []
        }
      },
    },
    computed: {
      ...mapGetters('tree', {
        industryTree: 'industryTag',
        areaTree: 'area',
      }),
    },
    watch: {
      'form.addrs'(val: string) {
        if (val) {
          // @ts-ignore
          this.$refs.ruleForm.validateField('addrs')
        }
      },
    },
  }

  if (selectKey) {
    selectKey.forEach((d) => {
      mixin.watch[`form.${d.key}`] = function (val: string | string[]) {
        if (Array.isArray(val)) {
          // @ts-ignore
          this.form[`${d.key}Label`] = val.map((s) => {
            const obj = this[d.options]?.find((o: IOptions) => o.value === s)
            return obj?.label
          })
        } else {
          const obj = this[d.options]?.find((o: IOptions) => o.value === val)
          // @ts-ignore
          this.form[`${d.key}Label`] = obj?.label
        }
      }
    })
  }

  if (treeKey) {
    treeKey.forEach((d) => {
      mixin.watch[`form.${d.key}`] = function () {
        // @ts-ignore
        const nodes = this.$refs[d.refName].getCheckedNodes()
        console.log(nodes)
        // @ts-ignore
        this.form[`${d.key}Label`] = nodes.map((n) => n?.label)
      }
    })
  }

  return mixin
}
